package com.chang.multithread.ReentrantLock;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
//Condition可以创建多个waitset(休息室)
//通过await的方法进入对应的waitset(休息室)
//通过signal唤醒对应的waitset(休息室)
//通过signal唤醒所有的waitset
@Slf4j
public class Conditional {
    static final  Object room=new Object();
    static ReentrantLock Room= new ReentrantLock();
    static Condition waitAfflatusSet=Room.newCondition();
    static Condition waitTakeoutSet=Room.newCondition();
    static volatile  boolean hasAfflatus=false; //有没有灵感
    static volatile  boolean hasTakeout=false; //有没有外卖

    public static void main(String[] args) {
    new Thread(()->{
        Room.lock();
        try {
        log.debug("有灵感么?【{}】",hasAfflatus);
        while (!hasAfflatus){
            log.debug("没灵感，休息一下");
            try {
                waitAfflatusSet.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            log.debug("灵感来了，准备开工");
        }
        }finally {
            Room.unlock();
        }
    },"t1").start();

    new Thread(()->{
        Room.lock();
        try {
        log.debug("有外卖么?【{}】",hasTakeout);
        while (!hasTakeout){
            log.debug("没灵感，休息一下");
            try {
                waitTakeoutSet.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            log.debug("外卖来了，肚子饱了，准备开工");
        }
        }finally {
            Room.unlock();
        }
    },"t2").start();

        log.debug("主线程开动");
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        new Thread(()->{
        Room.lock();
        try {
            hasAfflatus=true;
            waitAfflatusSet.signal();  //唤醒这个休息室的一个线程
        }finally {
            Room.unlock();
        }
        },"送灵感的").start();

        new Thread(()->{
        Room.lock();
        try {
            hasTakeout=true;
            waitTakeoutSet.signal();  //唤醒这个休息室的一个线程
        }finally {
            Room.unlock();
        }
        },"送外卖的").start();
    }
}
